const wx2my = require('../../wx2my');

// pages/user_coupons/user_coupons.js
// import{request} from"../request/index.js";
// import regeneratorRuntime from '../../utils/runtime.js';
const app = getApp();
let page = 1;
let totalpage;
Page({
  data: {
    goodsList: []
  },
  onLoad: function (options) {},
  onReady: function () {},
  onShow: function () {
    page = 1;
    this.get_list(); // this.getGoodsList()
  },

  //获取商品列表数据
  //   async getGoodsList(){
  //     const res = await request('user_coupon',{'token':wx.getStorageSync('token'),'page':page});
  //     //获取总条数
  //    if(res.data.code == 1){
  //      if(page == 1){
  //        totalpage = res.data.data.totalpage
  //      }
  //     this.setData({
  //       //拼接的数组
  //       goodsList:[...this.data.goodsList,...res.data.data.list],
  //       lock: totalpage <= page ? true : false   //如果totalpage小于等于page
  //     })
  //     //关闭下拉刷新的窗口
  //     wx.stopPullDownRefresh()
  //    } 
  // },
  get_list() {
    let that = this;
    app.wxRequest('user_coupon', {
      'token': wx2my.getStorageSync('token'),
      'page': page
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        let list = res.data.data.list;
        const regexp = /(?:\.0*|(\.\d+?)0+)$/;
        res.data.data.list.forEach(item => {
          item.money = item.money.replace(regexp, '$1');
        });

        if (page == 1) {
          totalpage = res.data.data.totalpage;
        }

        that.setData({
          list: page == 1 ? list : that.data.list.concat(list),
          lock: totalpage <= page ? true : false
        });
      }
    });
  },

  scan() {
    let that = this;
    wx2my.scanCode({
      success: res => {
        console.log(res);
        var res = res.result;

        if (res.indexOf('coupon_id') < 0) {
          wx2my.showToast({
            icon: 'none',
            title: '二维码无效'
          });
        } else {
          let coupon_id = app.fm.getUrlParam('coupon_id', res);
          that.setData({
            coupon_id: coupon_id
          });
          that.get_coupon();
        }
      }
    });
  },

  get_coupon() {
    let that = this;
    app.wxRequest('receive_coupon', {
      'token': wx2my.getStorageSync('token'),
      'coupon_id': that.data.coupon_id
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        app.toast(res.data.msg);
        page = 1;
        that.get_list();
      } else {
        app.toast(res.data.msg);
      }
    });
  },

  onHide: function () {},
  onUnload: function () {},
  onPullDownRefresh: function () {},
  onReachBottom: function () {
    page++;

    if (!this.data.lock) {
      this.get_list();
    }
  },
  onShareAppMessage: function () {}
});